<template>
	<div class="topPanel">
		<!-- <div class="-goback" @click="com.goBack()"></div> -->
		<div style="min-width:30px;">&nbsp;</div>
		<div class="appTitle">章鱼借阅</div>
	</div>
	<view class="bg-gray h-100" style="height: 100vh;">
		<div class="block-header-bg-color">
			<div class="d-flex w-100 a-center">
				<div class="f1 d-flex a-center">
					<div @click="goAccount" :class="userData.avator===''?'avatar':'avatar'"
						:style="'background-image:url(\''+userData.avator+'\');'"></div>
					<div v-if="needLogin===true">
						<button class="text-large -login-btn" @tap="getUserProfile">点击登录</button>
					</div>
					<div v-if="needLogin===false" @click="goAccount" class="text-large">{{userData.member_nickname}}
					</div>
					<div v-if="userData.is_vip===true" class="bg-image -vip1"></div>
				</div>
				<!-- <div v-if="needLogin==false" class="text-small d-flex a-center" @click="scanDevice">
					<div class="-icon -device" style="margin-top: 0;border-radius: 100px;margin-right:2px;"></div>
					<div class="text-gray">{{jyData.jy_name?jyData.jy_name:"扫码绑设备"}}</div>
				</div> -->
			</div>
			<div class="member-status">
				<div class="f1 d-flex a-center">
					<div>{{userData.is_vip==false?'开通图书会员':'我的图书会员'}}</div>
					<div class="-vip">vip</div>
				</div>
				<div @click="openService" :class="userData.is_vip!==true?'btn-colorful':'text-white text-small py-1'">
					{{userData.is_vip==true?'会员有效期至:'+userData.end_vip_date:'立即开通'}}
				</div>
			</div>
		</div>

		<!-- box -->
		<div class="block-box">
			<div class="text-bold text-large">我的订单</div>
			<div class="d-flex a-center j-center" style="margin-top: 15px;">
				<div class="f1 text-center" @click="goRecord(0)">
					<div class="bg-image -order -order0"></div>
					<div>全部订单</div>
				</div>
				<div class="f1">
					<div class="bg-image -order -order1" @click="goRecord(1)"></div>
					<div class="text-center">已借阅</div>
				</div>
				<div class="f1">
					<div class="bg-image -order -order2" @click="goRecord(2)"></div>
					<div class="text-center">已归还</div>
				</div>
			</div>
		</div>

		<!-- scan btn -->
		<div v-if="showOpenBtn" class="scan-btn-bar">
			<div class="scan-btn" @click="scanDevice">
				<div class="-open_door"></div>
				<div class="t">开门</div>
			</div>
		</div>

		<!-- 授权登陆窗 -->
		<template v-if="showLoginWindow===true">
			<div class="loginWindow">
				<div class="inner">
					<div class="title">请点击授权小程序授权登录</div>
					<div class="body">点击小程序授权登录按钮,可以使用小程序授权手机号登录</div>
					<div class="confrimBtn">
						
						<button class="confirm" open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber">小程序授权登录</button>
							<button class="cancle" @tap="showLoginWindow=false">取消</button>
					</div>
				</div>
			</div>
		</template>
	</view>
</template>

<script>
	import com from '../common/index.js'
	export default {
		data() {
			return {
				showOpenBtn: false,
				userData: {
					is_vip: false,
					end_vip_date: "2024/12/19",
					avator: "https://www.zyts.cc/static/wx_xcx/default_head.png", // "/static/images/avatar.png",
					member_name: ""
				},
				com: com,
				needLogin: false,
				showLoginWindow: false,
				jyID: '',
				jyData: {}
			}
		},
		onLoad(options) {
			if (uni.getSystemInfoSync().uniPlatform === 'mp-weixin') {
				const op = uni.getLaunchOptionsSync();
				if (op.scene == 1011 || op.scene == 1012 || op.scene == 1013) {
					const data = decodeURIComponent(options.q).split('?');
					const query = data.length > 1 ? data[1] : undefined;
					if (query) {
						const params = function(query) {
							const params = query.split('&');
							let obj = {};
							params.forEach(item => {
								const data = item.split('=');
								obj[data[0]] = data[1];
							});
							return obj;
						}(query);

						console.log('扫码进入', params.qrcode);
						uni.login({
							success: (res) => {
								uni.request({
									url: `https://www.zyts.cc/machine/api/home/login.php`,
									data: {
										code: res.code,
										qrcode: params.qrcode,
										login_type: 'library_user_login'
									},
									success: (res) => {
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										})
									},
									fail: (err) => {
										uni.showToast({
											title: err,
											icon: 'none'
										})
									}
								});
							}
						})
					}
				}
			}

			const that = this
			if (options.scene) {
				that.exCode(options.scene, () => {
					//that.scan2open()
				})
			}
			// else {
			// 	uni.showModal({
			// 		title: "请扫描借阅机上的二维码",
			// 		success: (res) => {
			// 			if (res.cancel) {
			// 				uni.exitMiniProgram();
			// 			}
			// 			if (res.confirm) {
			// 				uni.scanCode({
			// 					onlyFromCamera: true,
			// 					success: function(res) {
			// 						if (res.path) {
			// 							that.exCode(res.path)
			// 						}
			// 					}
			// 				});
			// 			}
			// 		}
			// 	})
			// }
		},
		onShow() {
			const that = this
			const keys = uni.getStorageSync('uToken')
			if (keys) {
				this.keys = keys
				com.getUser(keys, (e) => {
					//console.log(e)
					if (e == '266') {
						that.needLogin = true
						return
					}
					this.userData = e
				})
			} else {
				//请登录
				this.needLogin = true
			}
			that.com.canDisplayOpenBtn().then(e => {
				that.showOpenBtn = e
			})
		},
		methods: {
			// 扫码开门
			scan2open() {
				const that = this
				if (that.needLogin === true) {
					uni.showToast({
						title: "请先登陆",
						icon: 'error'
					})
					return
				}
				if (!that.jyData.jy_id) {
					uni.showToast({
						title: "请绑定设备",
						icon: 'error'
					})
					return
				}
				//that.loginThenOpendoor()
			},
			// 先登陆，后开门，组合
			loginThenOpendoor() {
				uni.showLoading({
					title: '请稍后'
				})
				const that = this
				const key = uni.getStorageSync('uToken')
				uni.request({
					url: that.com.serviceURL + '/cmobile/index.php?app=borrowing_info&mod=return_login&jy_id=' +
						that.jyID + '&key=' + key,
					success: e => {
						if (e.data.state !== 200) {
							uni.showToast({
								title: e.data.msg,
								icon: 'error',
								duration: 2000
							})
							uni.hideLoading({
								noConflict: true
							})
							return
						}
						uni.request({
							url: that.com.serviceURL +
								'/cmobile/index.php?app=borrowing_info&mod=open_door&jy_id=' +
								that.jyID + '&key=' + key,
							success: e => {
								uni.hideLoading({
									noConflict: true
								})
								uni.showToast({
									title: e.data.msg,
									icon: e.data.state == 200 ? 'success' : 'success',
									duration: 2000
								})
							}
						})
					}
				})
			},
			// 解析二维码的参数 并获取设备信息
			exCode(opt, callback = null) {
				//console.log(opt)
				let url = decodeURIComponent(opt)
				//console.log(url)
				const param = this.com.getParams(url)
				//console.log(param)
				const that = this
				if (param.jy_id) {
					that.jyID = param.jy_id
					that.com.getDeviceData(param.jy_id, (data) => {
						that.jyData = data
						if (callback) callback()
					})
				}
			},
			// 手动扫码获取设备信息
			scanDevice() {
				const that = this
				if (that.jyData.jy_id) {
					// 已有设备信息，直接开门
					console.log('已获取设备')
					that.loginThenOpendoor()
					return
				}
				// 无设备信息，调用扫码
				// 先提示
				uni.showModal({
					title: "提示",
					content: "请扫描书柜上的二维码",
					success: res => {
						if (res.confirm) {
							uni.scanCode({
								onlyFromCamera: true,
								success: function(res) {
									if (res.path) {
										let ps = that.com.getParams(res.path)
										if (!ps.scene) {
											uni.showToast({
												title: "读码失败",
												icon: 'error'
											})
											console.log('not scene')
											return
										}
										that.exCode(ps.scene, () => {
											that.scan2open()
										})
									} else {
										uni.showModal({
											title: "请扫描正确的机器码",
											showCancel: false
										})
										return
									}
								}
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 自动注册
			getUserProfile() {
				const accountInfo = uni.getAccountInfoSync();
				const appid = accountInfo.miniProgram.appId;
				console.log('appID:'+appid)
				const that = this
				// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				uni.getUserProfile({
					desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						if (res.errMsg == "getUserProfile:ok") {
							let userinfo = res.userInfo;
							that.userData.avatar = userinfo.avatarUrl
							let jmData = {
								encryptedData: res.encryptedData,
								iv: res.iv,
								rawData: res.rawData,
								siguature: res.siguature
							}
							uni.showLoading({
								title: "请稍等"
							})
							uni.login({
								success: (e) => {
									console.log(e)
									uni.request({
										method: 'get',
										url: that.com.serviceURL +
											"/cmobile/index.php?app=borrowing_login&mod=xcx_login",
										data: {
											code: e.code,
											userinfo: userinfo,
											jmData: jmData
										},
										success: e => {
											let data
											if (e.data.data.state == "100") {
												data = e.data.data.reinfo
												that.keys = data.keys
												that.openid = data.openid
												that.showLoginWindow = true
												// com.getUser(data.keys, (e) => {
												// 	//console.log(e)
												// 	if (e == '266') {
												// 		that.needLogin = true
												// 		return
												// 	}
												// 	that.userData = e
												// })
											} else if (e.data.data.state == '200') {
												data = e.data.data
												uni.setStorageSync('uToken', data
													.token)
												that.com.getUser(data.token, (res) => {
													that.needLogin = false
													that.userData = res
												})
											} else {
												console.error(e)
											}
											uni.hideLoading()
										}
									})
								}
							})
						} else {
							console.log(res)
						}
					},
					fail: err => {
						console.log(err)
					}
				})
			},
			// 获取用户手机
			getPhoneNumber(e) {
				const that = this
				let phonedata, phonedataiv
				//console.log(e)
				if (e.detail.errMsg !== 'getPhoneNumber:ok') return
				if (!that.keys) {
					console.log('no keys');
					return
				}
				phonedata = e.detail.encryptedData;
				phonedataiv = e.detail.iv;
				uni.request({
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: 'post',
					url: that.com.serviceURL + '/cmobile/index.php?app=borrowing_login&mod=gzh_auto_register_xcx',
					data: {
						phonedata: phonedata,
						phonedataiv: phonedataiv,
						client: 'wx_xcx',
						keys: that.keys
					},
					success: res => {
						//console.log(res)
						/*
						"{state: 200, 
						msg: \"登录成功\",
						data: {
							username: \"15939223870\", 
							key: \"64781b3407342c0989851cf1c2768671\", 
							red_money: 0,
							red_img: \"https://www.zyts.cc/static/defualt_img/sld_wap_new_reg_red.png\",
						}
						*/
						let data = res.data.data
						uni.showToast({
							title: res.data.msg
						})
						if (res.data.state == 200) {
							that.showLoginWindow = false
							that.needLogin = false
							that.userData.avator = data.red_img
							that.userData.member_name = data.username
						}
						uni.setStorageSync('uToken', data.key)
						// that.com.getUser(data.key, (res) => {
						// 	console.log(res)
						// 	that.needLogin = false
						// 	that.showLoginWindow=false
						// 	that.userData = res
						// })
					}
				})
			},
			// 跳转到usercenter或登陆
			openService() {
				if (this.needLogin === true) {
					uni.showToast({
						title: '请登录',
						icon: 'error',
						duration: 2000
					})
					return
				}
				this.com.go('usercenter')
			},
			// 跳转到record或登陆
			goRecord(recType) {
				if (this.needLogin === true) {
					uni.showToast({
						title: '请登录',
						icon: 'error',
						duration: 2000
					})
					return
				}
				this.com.go('record?action=' + recType)
			},
			// 跳转到信息修改
			goAccount() {
				if (this.needLogin === true) {
					uni.showToast({
						title: '请登录',
						icon: 'error',
						duration: 2000
					})
					return
				}
				com.go('account')
			}
		}
	}
</script>

<style>

</style>